'use strict';
const { axios } = require('../public/httpHelper');
const qs = require('qs');
const configDefault = require('../../config/config.default')();
const {keys} = configDefault;
const jwt = require('jsonwebtoken');
async function refreshAccessToken(refreshToken) {
  const data = qs.stringify({
    grant_type: 'refresh_token',
    client_id: configDefault.authorization.clientId,
    client_secret: configDefault.authorization.clientSecret,
    refresh_token: refreshToken,
  });
  const config = {
    method: 'post',
    url: `${configDefault.authorization.url}/users/token`,
    data,
  };
  try {
    const response = await axios(config);
    return response;
  } catch (error) {
    console.log('==================================================');
    console.log('刷新token出错了', error.response.data);
    console.log('==================================================');
    return null;
  }
}
async function authorization(accessToken) {
  const config = {
    method: 'get',
    url: `${configDefault.authorization.url}/users/authenticate`,
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  };
  try {
    // 去授权中心判断accessToken是否有效
    // const response = await axios(config);
    // return response
    //现在改为不去请求授权中心判断token是否有效了。现在改为使用jwt认证
    let decoded = jwt.verify(accessToken, keys);
    if(new Date(decoded.accessTokenExpiresAt)>Date.now()){
      return {
        data:{
          msg:'successed!'
        }
      }
    }else if(new Date(decoded.accessTokenExpiresAt)<=Date.now()){
      return {
        code:401
      };
    }
  } catch (error) {
    console.log('==================================================');
    console.log('判断token是否有效的请求得到error', error);
    console.log('==================================================');
    return null;
  }
}
module.exports = options => {
  return async function judgeSession(ctx, next) {
    const cookieStr = ctx.cookies.get('token', {
      httpOnly: true,
      signed: true, // 对cookie进行签名 防止用户修改cookie
      encrypt: true, // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密,这里要注意配置文件里的cookie.key和授权中心的key保持一致
    });
    if (ctx.request.url === '/tenantadminlistall' || ctx.request.url === '/login'
    ||ctx.request.url ==='/tenantadminInitCloudOltServer'
    || ctx.request.url === '/globallogin'
    || ctx.request.url.indexOf('/tenantadminlist') !== -1
    || ctx.request.url.indexOf('/tenantadmintr069init') !== -1
    || ctx.request.url.indexOf('/tenantadminInitACS') !== -1
    || ctx.request.url.indexOf('/tenantadmininit') !== -1) {
      await next();
    } else {
      if (!cookieStr) {
        console.log('token==undefined');
        return;
      }
      const cookieObj = JSON.parse(cookieStr);
      const { accessToken, refreshToken } = cookieObj;
      const response = await authorization(accessToken);
      if (response && response.data && response.data.msg === 'successed!') {
        await next();
      } else if (response && response.code === 401) {
        const newResponse = await refreshAccessToken(refreshToken);
        if (newResponse) {
          await next();
          ctx.cookies.set('token', JSON.stringify(newResponse.data), {
            maxAge: 1000 * 3600 * 24, // cookie存储一天 设置过期时间后关闭浏览器重新打开cookie还存在
            httpOnly: true, // 仅允许服务获取,不允许js获取
            signed: true, // 对cookie进行签名 防止用户修改cookie
            encrypt: true, // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密
            // domain: 'haha.com',
            path: '/',
            secure: false,
          });
        } else {
          ctx.status = 401;
          ctx.body = {
            msg: 'login timeout',
          };
        }
      } else {
        console.log('response 状态异常');
        return;
      }

    }
  };
};
